package com.example.mannortycoon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mannortycoon.dao.UserDao;
import com.example.mannortycoon.entity.UserEntity;
import com.example.mannortycoon.service.UserService;
import com.example.mannortycoon.uitl.JWTUtils;
import com.example.mannortycoon.uitl.PageUtils;
import com.example.mannortycoon.uitl.Query;
import com.example.mannortycoon.uitl.R;
import com.example.mannortycoon.vo.UserInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public R login(UserEntity userEntity) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("username", userEntity.getUsername());
        UserEntity user = this.getOne(wrapper);
        if (user == null) {
            return R.error("该用户不存在");
        } else if (!user.getPassword().equals(userEntity.getPassword())) {
            return R.error("用户名或密码错误");
        }else if(user.getStatus() == 0){
            return R.error("该用户已被锁定");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("id", user.getUserId());
        map.put("password", user.getPassword());
        String token = JWTUtils.getToken(map);
        return R.ok().put("token", token);
    }

    @Override
    public UserInfo getUserInfo(Long userId) {
        UserEntity userEntity = this.getById(userId);
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userEntity,userInfo);
        return userInfo;
    }

    @Override
    public List<UserEntity> getUserInfoListByIds(List<Long> collect) {
        if(collect.size() == 0){
            return new ArrayList<>();
        }
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.in("user_id",collect).select("user_id","username");
        return this.list(wrapper);
    }

    @Override
    public List<UserEntity> selectUsers(String username) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.like("username",username).select("username","user_id");
        return this.list(wrapper);
    }

    @Override
    public UserEntity getByUsername(String username) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        return this.getOne(wrapper);
    }
}
